package com.gdit.zax.utils;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;


/**
 * 处理提交enctype="multipart/form-data"的表单，文件则保存FileItem数据
 * @author user
 *
 */
public class FromRequest {
	private HashMap<String, Object> data = new HashMap<String, Object>();
	public Object getParameter (String key) {
		if (data!= null) {
			return data.get(key);
		} else {
			return null;
		}
	}
	
	public String getParameterString (String key) {
		Object obj = getParameter(key);
		if (obj != null) {
			return obj.toString();
		} else {
			return null;
		}
	}
	
	public void setParameter (String key,Object object) {
//		if (object!=null) 
//		System.out.println("setParameter:" + key +"=" +object.toString());
		if (data == null) {
			data = new HashMap<String, Object>();
		} 
		data.put(key, object);
	}
	
	//从表当获取新数据
	public FromRequest (ServletContext sc,HttpServletRequest request, HttpServletResponse response) {
		
		DiskFileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		try {
			List items = upload.parseRequest(request);// 上传文件解析
			Iterator itr = items.iterator();// 枚举方法
			while (itr.hasNext()) {
				FileItem item = (FileItem) itr.next();
				if (item.isFormField()) {// 判断是文件还是文本信息
					this.setParameter(item.getFieldName(), UrlDecoder.getUtf8String(item.getString()));
					LogUtil.print("参数>>" +item.getFieldName() + ":" + UrlDecoder.getUtf8String(item.getString()));
				} else {
					//未排除出现多个文件的可能
					if (item.getName() != null && !item.getName().equals("")) {// 判断是否选择了文件
						this.setParameter(item.getFieldName(), item);
					} else {
						this.setParameter(item.getFieldName(), null);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
